// pages/login/login.js

let account = ""
let password = ""
let confirmed_pwd = ""
const SERVER = require("../../interfaces/interface")
const APP = getApp()
const VEH = require("../../interfaces/vehicles")

Page({
  /**
   * 页面的初始数据
   */
  data: {
    account: "",
    password: "",
    confirmed_pwd: "",
    is_login_page: false,
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options !== undefined) {
      // options来自于导航到该页面的url后部参数
      // 此处用于实现区分登录和注册页面
      this.setData({
        is_login_page: (options.action == "login")
      })
    }
  },

  passwdInput(event) {
    let pwd = event.detail.value
    let pwd_format = /^.{1,32}$/i
    let kind = event.target.dataset.kind
    if (kind == 1) {
      // 输入密码
      if (pwd_format.test(pwd)) {
        password = pwd
      } else if (pwd != "") {
        // 密码错误，报错，并清空之前的密码记录
        wx.showToast({
            title: "密码过长",
            icon: "error",
            duration: 1000
          }),
          password = ""
      } else {
        password = ""
      }
    } else {
      // 注册页面，并且来自确认输入框
      confirmed_pwd = pwd
    }
  },

  accountInput(event) {
    let acc = event.detail.value
    let email_format = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/i
    if (email_format.test(acc)) {
      account = acc
    } else if (acc != "") {
      wx.showToast({
        title: "邮箱格式错误",
        icon: "error",
        duration: 1000
      })
      account = ""
    } else {
      account = ""
    }
  },

  async confirm(event) {
    if (this.data.is_login_page) {
      // 登录页处理
      this.loginProcess()
    } else {
      // 注册页处理
      this.registerProcess()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      account: "",
      password: "",
      confirmed_pwd: "",
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  async loginProcess() {
    if (account != "" && password != "") {
      wx.showLoading({
        title: "登陆中，请稍后",
        mask: true
      })
      let result = await SERVER.login(account, password)
      if (result.status=="success") {
        // 获取用户信息
        let result = await SERVER.queryUserInfo()
        wx.hideLoading()
        console.log("查询用户信息",result)
        if(result.status=="success")
        {
          let info = result.res
          APP.setAccountInfo({
            account: info.account,
            nickName: info.name
          })
          VEH.refreshVehicles(info.car_array)
          wx.navigateBack()
          wx.showToast({
            title: '登陆成功',
            icon:"success",
          })
        }
        else
        {
          wx.showToast({
            title: '服务器异常',
            icon:"error",
            duration:1500
          })
          SERVER.logout()
        }
      }
      else if (result.status=="fail") {
        wx.showToast({
          title: result.res.msg,
          icon: "error"
        })
      }
      else{
        wx.showToast({
          title: '网络请求错误',
          icon: "error"
        })
      }
    } else {
      wx.showToast({
        title: "请确认账号密码",
        icon: "error"
      })
    }
  },

  checkPasswordConstrain() {
    if (account == "") {
      wx.showToast({
        title: "请确认账号正确",
        icon: "error",
        duration: 1000
      })
    } else if (password == "") {
      wx.showToast({
        title: "请确认密码正确",
        icon: "error",
        duration: 1000
      })
    } else if (password != confirmed_pwd) {
      wx.showToast({
        title: "两次密码不一致",
        icon: "error",
        duration: 1000
      })
    } else {
      return true
    }
    return false
  },

  async registerProcess() {
    if (this.checkPasswordConstrain()) {
      let name
      try
      {
        name = await new Promise(function (resolve, reject) {
          wx.showModal({
            title: "你的昵称是？",
            editable: true,
            placeholderText: "不超过7个汉字长度",
            success: (res) => {
              console.log(res)
              if (res.confirm) resolve(res.content)
              else reject("cancel")
            },
            fail: () => {
              reject("fail")
            }
          })
        })
      }
      catch(error)
      {
        console.log("昵称输入界面取消")
        return
      }
      wx.showLoading({
        title: "注册中，请稍后",
        mask: true
      })
      try
      {
        let result = await SERVER.register(account, password, name)
        if (result.status=="success") {
          APP.setAccountInfo({
            account: account,
            nickName: name
          })
          wx.navigateBack({
            delta: 1,
          })
        } else if(result.status=="fail"){
          wx.showToast({
            title: result.res.msg
          })
        }
        else{
          wx.showToast({
            title: "网络错误"
          })
        }
      }
      catch(error)
      {
      }
      wx.hideLoading()
    }
  },

})